<template>
  <div class="app-container">
    <el-button type="primary" icon="el-icon-circle-plus-outline" size="small" @click="showCreate()"
               v-permission="'banner:add'">添加
    </el-button>
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row>

      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>


      <el-table-column label="封面" width="900px">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" class="banner-img" style="width:800px">
        </template>
      </el-table-column>

      <el-table-column prop="title" label="标题" width="80"/>

      <el-table-column prop="linkUrl" label="链接地址" width="100"/>

      <el-table-column prop="gmtCreate" label="添加时间" sortable width="170"/>

      <el-table-column prop="sort" label="排序" sortable width="80"/>

      <el-table-column label="首页显示" width="80" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="disabledBanner(scope.row)"
          />
        </template>
      </el-table-column><el-table-column label="操作" width="200" align="center" >
        <template slot-scope="scope">
          <el-button-group>
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showUpdate(scope.$index)" v-permission="'banner:update'">修改</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.id)">删除</el-button>
          </el-button-group>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      background
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />

    <!--新增修改-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="15vh" width="800px">
      <el-form label-width="120px">
        <el-form-item label="banner标题">
          <el-input v-model="banner.title" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="封面">

          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :action="BASE_URL+'/eduoss/fileoss?host=banner'"
            class="avatar-uploader">
            <img v-if="banner.imageUrl" :src="banner.imageUrl" style="max-width: 600px">
            <el-button type="primary" v-else>上传<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-upload>
          <label class="form-tip"><i class="el-icon-warning"></i> 推荐1770×360</label>

        </el-form-item>
        <el-form-item label="链接地址">
          <el-input v-model="banner.linkUrl" controls-position="right" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="banner.sort" controls-position="right" :min="0" :max="100"/>
        </el-form-item>


        <el-form-item>
          <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>

</template>

<script>
  const defaultForm = {
    title: '',
    imageUrl:  process.env.OSS_PATH+"/banner/banner.png",
    linkUrl: '',
    sort: ''
  }
  export default {
    data() {
      return {
        listLoading: true, // 是否显示loading信息
        list: null, //查询后返回数据
        page: 1, //当前页
        limit: 3, //每页记录数
        total: 0, //总记录数
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '添加轮播图'
        },
        banner: defaultForm
        , BASE_URL: process.env.BASE_URL//获取dev.env.js中的BASE_API
        , saveBtnDisabled: false // 保存按钮是否禁用,

      }
    },created() {
      this.getList()
    },
    methods: {
      //获取列表
      getList(page = 1) {
        this.page = page
        this.api({
          url: `/banner/pageBanner/${this.page}/${this.limit}`,
          method: "get",
        }).then(response => {
            this.list = response.list //列表
            this.total = response.totalCount //总数
            this.listLoading = false
          }) //请求成功
          .catch(error => {
            console.log(error)
          })//请求失败
      },
      // 删除
      removeDataById(id) {
        // debugger
        //MessageBox 在utils/request.js中已引用
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return this.api({
            url: `/banner/${id}`,
            method: "delete",
          })
        }).then(() => {
          this.getList(this.page)
          this.$message.success("删除成功")
        }).catch((response) => { // 失败
          if (response === 'cancel') {
            this.$message.info('已取消删除')
          } else {
            this.$message.error('删除失败')
          }
        })
      },showUpdate($index) {
        //显示修改对话框
        this.banner = Object.assign({}, this.list[$index]);//深拷贝
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      showCreate() {
        //显示新增对话框
        this.banner = {};
        this.dialogStatus = "create"
        this.dialogFormVisible = true
      },
      saveOrUpdate() {
        this.saveBtnDisabled = true
        if (!this.banner.id) {
          this.saveData()
        } else {
          this.updateData()
        }
      },
      // 保存
      saveData() {
        this.api({
          url: `/banner/addBanner`,
          method: "post",
          data:this.banner
        }).then(response => {
          this.reloadList()
          return this.$message.success('保存成功!')
        }).catch((response) => {
          this.$message.error('保存失败')
        })
      },
      // 根据id更新记录
      updateData() {
        this.saveBtnDisabled = true
          this.api({
            url: `/banner/update`,
            method: "put",
            data:this.banner
          }).then(response => {
            this.reloadList()
          return this.$message.success('修改成功!')
        }).catch((response) => {
          this.$message.error('保存失败')
        })
      },
      reloadList(){
        this.getList(this.page)
        this.dialogFormVisible=false
        this.saveBtnDisabled=false
      },
      //5. 上传封面成功调用的方法
      handleAvatarSuccess(res, file) {
        this.banner.imageUrl = res.info

      },
      //6. 上传之前调用的方法 约定文件类型
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        const typeArr=['image/jpeg','image/png','image/jpg']
        const isImage=typeArr.find(x=>x===file.type);
        if (!isImage) {
          this.$message.error('不支持上传此文件类型!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isImage && isLt2M
      },
      disabledBanner(banner){
        console.log(banner)
        //switch 状态发生变化时的回调函数	新状态的值 banner.isShow为新值
        let tipText= banner.isShow ?'确定开启显示？':'确定关闭显示？';
        this.$confirm(tipText, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return this.api({
            url: `/banner/update`,
            method: "put",
            data:banner
          })
        }).then(() => {
          this.getList(this.page)
        }).catch((response) => {
          this.$message.error('保存失败')
        })

      }
    }
  }
</script>

<style scoped>
.banner-img{
  width: 300px;
}
</style>
